<template>
  <div class="homeContainer">
    <div class="centerBox">
      <div class="centerLeft">
        <div class="topBack">
          <span @click="clearDetailIndex"><i></i>新增订阅</span>
          <div class="deliveryRight">
            <div
              class="box"
              style="margin-right: 46px"
              @click="clearDetailIndex"
            >
              取消
            </div>
            <div
              class="box boxcur"
              style="margin-right: 16px"
              @click="handleSubscribe"
            >
              订阅
            </div>
          </div>
        </div>
        <div class="form-wrapper">
          <el-form
            :model="form"
            :rules="rules"
            label-width="120px"
            class="custom-form"
            ref="formRef"
          >
            <el-form-item label="订阅标题：" prop="title">
              <el-input v-model="form.title" placeholder="请输入" />
            </el-form-item>

            <el-form-item label="预测服务1：" prop="service1">
              <el-select
                v-model="form.service1"
                placeholder="请选择"
                @change="handleServiceChange(1)"
              >
                <el-option label="RAIM机场预测" value="1" />
                <el-option label="RAIM航路预测" value="2" />
                <el-option label="RAIM航线预测" value="3" />
                <el-option label="RAIM区域预测" value="4" />
                <el-option label="ADS-B航线预测" value="11" />
                <el-option label="ADS-B区域预测" value="12" />
              </el-select>
            </el-form-item>

            <el-form-item label="预测服务2：" prop="service2">
              <el-select
                v-model="form.service2"
                placeholder="请选择"
                @change="handleServiceChange(2)"
              >
                <el-option label="RAIM机场预测" value="1" />
                <el-option label="RAIM航路预测" value="2" />
                <el-option label="RAIM航线预测" value="3" />
                <el-option label="RAIM区域预测" value="4" />
                <el-option label="ADS-B航线预测" value="11" />
                <el-option label="ADS-B区域预测" value="12" />
              </el-select>
            </el-form-item>

            <el-form-item label="预测服务3：" prop="service3">
              <el-select
                v-model="form.service3"
                placeholder="请选择"
                @change="handleServiceChange(3)"
              >
                <el-option label="RAIM机场预测" value="1" />
                <el-option label="RAIM航路预测" value="2" />
                <el-option label="RAIM航线预测" value="3" />
                <el-option label="RAIM区域预测" value="4" />
                <el-option label="ADS-B航线预测" value="11" />
                <el-option label="ADS-B区域预测" value="12" />
              </el-select>
            </el-form-item>

            <el-form-item label="推送设置：" prop="pushSetting">
              <el-select v-model="form.pushSetting" placeholder="请选择">
                <el-option label="每天定时1次" value="1" />
                <el-option label="每天定时2次" value="2" />
              </el-select>
            </el-form-item>

            <el-form-item label="时间点1：" prop="timePoint1">
              <el-select v-model="form.timePoint1">
                <el-option
                  v-for="(hour, index) in [
                    '00:00',
                    '01:00',
                    '02:00',
                    '03:00',
                    '04:00',
                    '05:00',
                    '06:00',
                    '07:00',
                    '08:00',
                    '09:00',
                    '10:00',
                    '11:00',
                    '12:00',
                    '13:00',
                    '14:00',
                    '15:00',
                    '16:00',
                    '17:00',
                    '18:00',
                    '19:00',
                    '20:00',
                    '21:00',
                    '22:00',
                    '23:00',
                  ]"
                  :key="index"
                  :label="hour"
                  :value="index"
                />
              </el-select>
            </el-form-item>
            <el-form-item
              label="时间点2："
              prop="timePoint2"
              v-if="form.pushSetting === '2'"
            >
              <el-select v-model="form.timePoint2">
                <el-option
                  v-for="(hour, index) in [
                    '00:00',
                    '01:00',
                    '02:00',
                    '03:00',
                    '04:00',
                    '05:00',
                    '06:00',
                    '07:00',
                    '08:00',
                    '09:00',
                    '10:00',
                    '11:00',
                    '12:00',
                    '13:00',
                    '14:00',
                    '15:00',
                    '16:00',
                    '17:00',
                    '18:00',
                    '19:00',
                    '20:00',
                    '21:00',
                    '22:00',
                    '23:00',
                  ]"
                  :key="index"
                  :label="hour"
                  :value="index"
                />
              </el-select>
            </el-form-item>

            <el-form-item label="接收邮箱：" prop="email">
              <el-input v-model="form.email" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="订阅周期：" prop="period">
              <el-select v-model="form.period" placeholder="请选择">
                <el-option label="1个月" value="30" />
                <el-option label="3个月" value="90" />
                <el-option label="6个月" value="180" />
                <el-option label="12个月" value="365" />
                <el-option label="自定义天数" value="自定义天数" />
              </el-select>
            </el-form-item>
            <el-form-item
              label="自定义天数："
              prop="cusDay"
              v-if="form.period === '自定义天数'"
            >
              <el-input
                v-model.number="form.cusDay"
                placeholder="请输入"
                type="number"
                min="1"
              />
            </el-form-item>
          </el-form>
        </div>
      </div>
      <div class="centerRight">
        <div class="rightTop">
          <div
            @click="changeTabIndex(1)"
            :class="['rightBtn', { rightBtnCur: changeCurIndex == 1 }]"
          >
            {{ getServiceLabel(form.service1) }}
          </div>
          <div
            @click="changeTabIndex(2)"
            :class="['rightBtn', { rightBtnCur: changeCurIndex == 2 }]"
          >
            {{ getServiceLabel(form.service2) }}
          </div>
          <div
            style="margin-right: 0px !important"
            @click="changeTabIndex(3)"
            :class="['rightBtn', { rightBtnCur: changeCurIndex == 3 }]"
          >
            {{ getServiceLabel(form.service3) }}
          </div>
        </div>
        <div class="rightBottom">
          <div v-if="changeCurIndex == 1" class="tabBox dingyuerightInfo">
            <component
              :is="getComponentByService(1)"
              :airport-list="airportList"
              :options-list-satsys="optionsListSatsys"
              :options-list-angle="optionsListAngle"
              :options-list-algorithm="optionsListAlgorithm"
              :options-list-standard="optionsListStandard"
              :options-router-save-lists="optionsRouterSaveLists"
              :types-waypoint-lists="typesWaypointLists"
              :route-segments="getServiceFormData(1).routeSegments"
              :default-form-data="getServiceFormData(1)"
              :key="serviceFormData[0].updateKey"
              @update:formData="(data) => updateServiceForm(1, data)"
              @insertItem="() => handleRouteEdit('insert', 1)"
              @deleteItem="() => handleRouteEdit('delete', 1)"
              @addItem="() => handleRouteEdit('add', 1)"
            />
          </div>

          <div v-if="changeCurIndex == 2" class="tabBox dingyuerightInfo">
            <component
              :is="getComponentByService(2)"
              :airport-list="airportList"
              :options-list-satsys="optionsListSatsys"
              :options-list-angle="optionsListAngle"
              :options-list-algorithm="optionsListAlgorithm"
              :options-list-standard="optionsListStandard"
              :options-router-save-lists="optionsRouterSaveLists"
              :types-waypoint-lists="typesWaypointLists"
              :route-segments="getServiceFormData(2).routeSegments"
              :default-form-data="getServiceFormData(2)"
              :key="serviceFormData[1].updateKey"
              @update:formData="(data) => updateServiceForm(2, data)"
              @insertItem="() => handleRouteEdit('insert', 2)"
              @deleteItem="() => handleRouteEdit('delete', 2)"
              @addItem="() => handleRouteEdit('add', 2)"
            />
          </div>

          <div v-if="changeCurIndex == 3" class="tabBox dingyuerightInfo">
            <component
              :is="getComponentByService(3)"
              :airport-list="airportList"
              :options-list-satsys="optionsListSatsys"
              :options-list-angle="optionsListAngle"
              :options-list-algorithm="optionsListAlgorithm"
              :options-list-standard="optionsListStandard"
              :options-router-save-lists="optionsRouterSaveLists"
              :types-waypoint-lists="typesWaypointLists"
              :route-segments="getServiceFormData(3).routeSegments"
              :default-form-data="getServiceFormData(3)"
              :key="serviceFormData[2].updateKey"
              @update:formData="(data) => updateServiceForm(3, data)"
              @insertItem="() => handleRouteEdit('insert', 3)"
              @deleteItem="() => handleRouteEdit('delete', 3)"
              @addItem="() => handleRouteEdit('add', 3)"
            />
          </div>
        </div>
      </div>
    </div>
    <div class="footerTime">
      <p>当前时间(UTC)：{{ utcTime }}</p>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, watch } from "vue";
import { subscriptionsMeApi } from "@/api/tabOne";
import { airportsApi, getWayPointsApi } from "@/api/home";
import localStorageUtil from "@/utils/tools/localStorageUtil";
import {
  forecastTypesApi,
  typesWaypointApi,
  selectionsGetApi,
} from "@/api/tabOne";
import dayjs from "dayjs";
import RouteSituationForecast from "@/views/auth/components/RouteSituationForecast.vue";
import AirportForecast from "@/views/auth/components/AirportForecast.vue";
import RouteTimeSharing from "@/views/auth/components/RouteTimeSharing.vue";
import AreaStatistics from "@/views/auth/components/AreaStatistics.vue";
import { useTime } from "@/utils/tools/useTime";

const { utcTime, formatTimeHasDay, getDaysLaterFormatted } = useTime();
let airportList = ref([]); // 机场列表（机场组件用）
let optionsListAngle = ref([]); // 角度列表（通用）
let optionsListAlgorithm = ref([]); // 算法列表（通用）
let optionsListSatsys = ref([]); // 星座列表（通用）
let optionsListStandard = ref([]); // 最低运行标准（航路组件用）
let optionsRouterSaveLists = ref([]); // 已保存航路（航路组件用）
let typesWaypointLists = ref([]); // 航路节点列表（航线组件用）

const serviceDefaultMap = {
  1: { methods: 1, type: 1 }, // RAIM机场预测
  2: { methods: 1, type: 5 }, // RAIM航路预测
  3: { methods: 1, type: 7 }, // RAIM航线预测
  4: { methods: 1, type: 4 }, // RAIM区域预测
  11: { methods: 2, type: 7 }, // ADS-B航线预测
  12: { methods: 2, type: 4 }, // ADS-B区域预测
};

// 表单数据：左侧服务选择
const form = reactive({
  title: "",
  service1: "1", // 默认服务1：机场预测
  service2: "2", // 默认服务2：航路预测
  service3: "3",
  pushSetting: "1",
  timePoint1: "",
  timePoint2: "",
  email: "",
  period: "30",
  cusDay: 1,
});

// 表单验证规则
const rules = reactive({
  title: [{ required: true, message: "请输入订阅标题", trigger: "blur" }],
  service1: [{ required: true, message: "请选择预测服务1", trigger: "change" }],
  service2: [{ required: true, message: "请选择预测服务2", trigger: "change" }],
  service3: [{ required: true, message: "请选择预测服务3", trigger: "change" }],
  pushSetting: [
    { required: true, message: "请选择推送设置", trigger: "change" },
  ],
  timePoint1: [
    // 时间点1始终必填（只要选了推送设置）
    { required: true, message: "请选择时间点1", trigger: "blur" },
  ],
  timePoint2: [
    // 时间点2仅在推送设置为2时必填
    {
      required: () => form.pushSetting === "2",
      message: "请选择时间点2",
      trigger: "blur",
    },
  ],
  email: [
    { required: true, message: "请输入接收邮箱", trigger: "blur" },
    {
      type: "email",
      message: "请输入正确的邮箱格式",
      trigger: ["blur", "change"],
    },
  ],
  period: [{ required: true, message: "请选择订阅周期", trigger: "change" }],
  cusDay: [
    // 自定义天数仅在period为空时必填，且为正整数
    {
      required: () => form.period === "自定义天数",
      message: "请输入自定义天数",
      trigger: "blur",
    },
    {
      validator: (rule, value, callback) => {
        if (
          form.period === "自定义天数" &&
          (!value || value < 1 || !Number.isInteger(value))
        ) {
          callback(new Error("请输入大于0的整数"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
});

// 右侧标签切换：默认显示服务1配置
let changeCurIndex = ref(1);
// 服务配置数据：存储3个服务的组件配置 - 初始数据独立-用于提交
const serviceFormData = ref([
  {
    type: "1",
    updateKey: 0,
    data: {
      airports: ["", "", "", "", ""],
      optionsListSatsysDefault: "",
      optionsListAngleDefault: "",
      optionsListAlgorithmDefault: "",
    },
  },
  {
    type: "2",
    updateKey: 0,
    data: {
      optionsListSatsysDefault5: "",
      optionsListAngleDefault5: "",
      optionsListAlgorithmDefault5: "",
      stdId5: "",
      routeCode5: "",
    },
  },
  {
    type: "3",
    updateKey: 0,
    data: {
      optionsListAngleDefault71: "",
      optionsListAngleDefault72: "",
      optionsListAngleDefault73: "",
      airport71: "",
      airport72: "",
      optionsListAlgorithmDefault7: "",
      stdId7: "",
      optionsListSatsysDefault7: "",
      selectedstartTimeDateTime7: null,
      flightHours7: "",
      flightMinutes7: "",
      typesWaypoint71: "",
      routeCode7: "",
      typesWaypoint72: "",
      routeSegments: [],
    },
  },
]);

// 表单引用：用于验证
const formRef = ref(null);

const changeTabIndex = (index) => {
  changeCurIndex.value = index;
};

// 左侧服务选择变化关
const handleServiceChange = async (serviceIndex) => {
  const serviceType = form[`service${serviceIndex}`];
  const targetService = serviceFormData.value[serviceIndex - 1];
  targetService.type = serviceType;
  console.log("切换服务类型:", serviceType, "服务索引:", serviceIndex);

  const defaultParams = serviceDefaultMap[serviceType];
  let defaultData = null;
  if (defaultParams) {
    // 调用对应接口获取默认值
    defaultData = await loadDefaultValues(
      defaultParams.methods,
      defaultParams.type
    );
  }
  if (serviceType === "1") {
    let airports = ["", "", "", "", ""];
    if (defaultData && Array.isArray(defaultData.airportCodes)) {
      airports = defaultData.airportCodes
        .slice(0, 5)
        .concat(Array(5 - defaultData.airportCodes.length).fill(""));
    }

    targetService.data = {
      airports: airports,
      optionsListSatsysDefault: defaultData?.params?.satSysId || "",
      optionsListAngleDefault: defaultData?.params?.angleId || "",
      optionsListAlgorithmDefault: defaultData?.params?.algorithmId || "",
    };
    console.log(
      "切换到RAIM机场预测，赋值airports:",
      targetService.data.airports
    );
  } else if (serviceType === "2") {
    // RAIM航路预测
    targetService.data = {
      optionsListSatsysDefault5: String(defaultData?.params?.satSysId || ""),
      optionsListAngleDefault5: String(defaultData?.params?.angleId || ""),
      optionsListAlgorithmDefault5: String(
        defaultData?.params?.algorithmId || ""
      ),
      stdId5: String(defaultData?.params?.stdId || ""),
      routeCode5: defaultData?.routeCode || "",
    };
  } else if (serviceType === "3" || serviceType === "11") {
    // RAIM/ADS-B航线预测
    const routeSegmentsNewArr =
      defaultData?.segments?.map((item) => ({
        entryWaypointName: item.entryWaypointName,
        routeCode: item.routeCode,
        exitWaypointName: item.exitWaypointName,
        checked: false,
      })) || [];

    targetService.data = {
      optionsListAngleDefault71: String(defaultData?.depAngleId || ""),
      optionsListAngleDefault72: String(defaultData?.destAngleId || ""),
      optionsListAngleDefault73: String(defaultData?.routeAngleId || ""),
      airport71: String(defaultData?.depAirport?.airportCode || ""),
      airport72: String(defaultData?.destAirport?.airportCode || ""),
      optionsListAlgorithmDefault7: String(defaultData?.routeAlgorithmId || ""),
      stdId7: String(defaultData?.routeStdId || ""),
      optionsListSatsysDefault7: String(defaultData?.satSysId || ""),
      selectedstartTimeDateTime7: defaultData?.startTime
        ? new Date(defaultData.startTime)
        : null,
      flightHours7: String(defaultData?.flightHours || "0"),
      flightMinutes7: String(defaultData?.flightMinutes || "0"),
      typesWaypoint71: "",
      routeCode7: "",
      typesWaypoint72: "",
      routeSegments: routeSegmentsNewArr,
    };
  } else if (serviceType === "4" || serviceType === "12") {
    // RAIM/ADS-B区域预测
    targetService.data = {
      optionsListSatsysDefault4: String(defaultData?.params?.satSysId || ""),
      optionsListAngleDefault4: String(defaultData?.params?.angleId || ""),
      optionsListAlgorithmDefault4: String(
        defaultData?.params?.algorithmId || ""
      ),
      handleAreaStartTime: defaultData?.period?.startTime
        ? new Date(defaultData.period.startTime)
        : null,
      handleAreaEndTime: defaultData?.period?.endTime
        ? new Date(defaultData.period.endTime)
        : null,
      autoUpdateTime: defaultData?.autoUpdateId || "0",
    };
  } else {
    targetService.data = {};
  }
  targetService.updateKey += 1;
  changeCurIndex.value = serviceIndex;
};

// 根据服务类型获取要渲染的组件：机场→AirportForecast，航路→RouteSituationForecast,航线-RouteTimeSharing
const getComponentByService = (serviceIndex) => {
  const serviceType = serviceFormData.value[serviceIndex - 1].type;
  if (serviceType === "1") return AirportForecast;
  if (serviceType === "2") return RouteSituationForecast;
  if (serviceType === "3" || serviceType === "11") return RouteTimeSharing;
  if (serviceType === "4" || serviceType === "12") return AreaStatistics;

  return { template: `<div class="empty-tip">该服务暂无配置项</div>` };
};

// 根据服务类型获取初始表单数据：返回对应服务的独立数据
const getServiceFormData = (serviceIndex) => {
  return serviceFormData.value[serviceIndex - 1].data;
};

// 接收组件的表单数据更新
const updateServiceForm = (serviceIndex, newData) => {
  const targetService = serviceFormData.value[serviceIndex - 1];
  // 深比较数据是否变化，避免重复赋值导致的循环渲染
  if (JSON.stringify(targetService.data) !== JSON.stringify(newData)) {
    targetService.data = newData;
    console.log(`服务${serviceIndex}配置更新（独立数据）:`, newData);
  }
};
const handleRunSubscribe = async (submitData) => {
  const { code } = await subscriptionsMeApi(submitData);
  if (code === 200) {
    clearDetailIndex();
  }
};
const getAirportByCode = (targetCode) => {
  return (
    airportList.value.find((airport) => airport.airportCode === targetCode) ||
    null
  );
};
// 订阅按钮
const handleSubscribe = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      const fcstRequests = serviceFormData.value.map((item) => {
        let paramsObj;
        if (item.type == 1) {
          paramsObj = {
            params: {},
            period: {},
            airportCodes: [],
          };
          paramsObj.params.algorithmId = item.data.optionsListAlgorithmDefault;
          paramsObj.params.angleId = item.data.optionsListAngleDefault;
          paramsObj.params.satSysId = item.data.optionsListSatsysDefault;
          paramsObj.period.endTime = localStorageUtil.get("endTime") || "";
          paramsObj.period.startTime = localStorageUtil.get("startTime") || "";
          paramsObj.airportCodes = [
            item.data.airports[0],
            item.data.airports[1],
            item.data.airports[2],
            item.data.airports[3],
            item.data.airports[4],
          ];
          return {
            forecastType: item.type, // 对应 serviceType
            forecastRequest: paramsObj, // 对应 config
          };
        } else if (item.type == 2) {
          paramsObj = {
            params: {},
            period: {},
          };
          paramsObj.params.algorithmId = item.data.optionsListAlgorithmDefault5;
          paramsObj.params.angleId = item.data.optionsListAngleDefault5;
          paramsObj.params.satSysId = item.data.optionsListSatsysDefault5;
          paramsObj.params.stdId = item.data.stdId5;
          const endDayTime = getDaysLaterFormatted(
            formatTimeHasDay(utcTime.value) + " 00:00:00"
          );
          paramsObj.period.endTime = endDayTime + " 00:00:00";
          paramsObj.period.startTime =
            formatTimeHasDay(utcTime.value) + " 00:00:00";
          +" 00:00:00";
          paramsObj.routeCode = item.data.routeCode5;
        } else if (item.type == 3 || item.type == 11) {
          paramsObj = {};
          const routeSegmentsArray = item.data.routeSegments.map(
            (innterItem) => {
              return {
                entryWaypointName: innterItem.entryWaypointName,
                routeCode: innterItem.routeCode,
                exitWaypointName: innterItem.exitWaypointName,
              };
            }
          );
          const getDepAirport = getAirportByCode(item.data.airport71);
          const depAirportObj = {
            airportCode: getDepAirport.airportCode,
            city: getDepAirport.city,
            elevation: getDepAirport.elevation,
            latitude: getDepAirport.latitude,
            longitude: getDepAirport.longitude,
            name: getDepAirport.name,
          };
          const getDestAirportObj = getAirportByCode(item.data.airport72);
          const destAirportObj = {
            airportCode: getDestAirportObj.airportCode,
            city: getDestAirportObj.city,
            elevation: getDestAirportObj.elevation,
            latitude: getDestAirportObj.latitude,
            longitude: getDestAirportObj.longitude,
            name: getDestAirportObj.name,
          };
          paramsObj = {
            airlineCode: item.data.airportRouterName7,
            depAirport: depAirportObj,
            destAirport: destAirportObj,
            depAngleId: item.data.optionsListAngleDefault71,
            destAngleId: item.data.optionsListAngleDefault72,
            routeAngleId: item.data.optionsListAngleDefault73,
            flightHours: item.data.flightHours7,
            flightMinutes: item.data.flightMinutes7,
            startTime: dayjs(item.data.selectedstartTimeDateTime7).format(
              "YYYY/MM/DD HH:mm:ss"
            ),
            forecastMode: "0",
            routeAlgorithmId: item.data.optionsListAlgorithmDefault7,
            routeStdId: item.data.stdId7,
            satSysId: item.data.optionsListSatsysDefault7,
            segments: routeSegmentsArray,
            // id: saveRouteId.value,
          };
        }
        return {
          forecastType: item.type,
          forecastRequest: paramsObj,
        };
      });

      // 构造目标格式的提交数据
      const submitData = {
        email: form.email,
        subBaseDays: form.period === "自定义天数" ? form.cusDay : form.period, // 区分自定义天数和固定周期
        subTimePoints: [form.timePoint1, form.timePoint2].filter(Boolean), // 过滤空值（避免时间点2未选择时传空）
        title: form.title,
        fcstRequests: fcstRequests,
      };
      handleRunSubscribe(submitData);
      console.log("最终提交数据（目标格式）:", submitData);
    } else {
      return false;
    }
  });
};

// 取消按钮：重置所有表单和独立服务数据
// const handleCancel = () => {
//   formRef.value.resetFields();
//   // 重置为初始独立数据（不共享）
//   serviceFormData.value = [
//     {
//       type: "1",
//       data: {
//         airports: ["", "", "", "", ""],
//         optionsListSatsysDefault: "",
//         optionsListAngleDefault: "",
//         optionsListAlgorithmDefault: "",
//       },
//     },
//     {
//       type: "2",
//       data: {
//         optionsListSatsysDefault5: "",
//         optionsListAngleDefault5: "",
//         optionsListAlgorithmDefault5: "",
//         stdId5: "",
//         routeCode5: "",
//       },
//     },
//     {
//       type: "3",
//       data: {
//         optionsListAngleDefault71: "",
//         optionsListAngleDefault72: "",
//         optionsListAngleDefault73: "",
//         airport71: "",
//         airport72: "",
//         optionsListAlgorithmDefault7: "",
//         stdId7: "",
//         optionsListSatsysDefault7: "",
//         selectedstartTimeDateTime7: null,
//         flightHours7: "",
//         flightMinutes7: "",
//         typesWaypoint71: "",
//         routeCode7: "",
//         typesWaypoint72: "",
//         routeSegments: [],
//       },
//     },
//   ];
//   // 切换到服务1面板
//   changeCurIndex.value = 1;
// };

// 加载所有下拉选项数据
const loadAllOptions = async () => {
  try {
    // 加载通用选项（角度、星座、算法、运行标准）
    const { code: typeCode, data: typeData } = await forecastTypesApi();
    if (typeCode === 200) {
      optionsListAngle.value = typeData.angle || [];
      optionsListAlgorithm.value = typeData.algorithm || [];
      optionsListSatsys.value = typeData.satsys || [];
      optionsListStandard.value = typeData.standard || [];
    }

    // 加载机场列表（机场组件用）
    const { code: airportCode, data: airportData } = await airportsApi();
    if (airportCode === 200) {
      airportList.value = airportData.list || [];
    }

    // 加载已保存航路列表（航路组件用）
    const { code: defaultRouteCode, data: defaultRouteData } =
      await getWayPointsApi();
    if (defaultRouteCode === 200) {
      const routeData = defaultRouteData.list.map((outerItem) => ({
        code: outerItem.code,
        id: outerItem.id,
      }));
      optionsRouterSaveLists.value = routeData;
    }
    // 加载航路节点列表（航线组件用）
    const { code: wayPointCode, data: wayPointData } = await typesWaypointApi({
      preType: 0,
    });
    if (wayPointCode === 200) {
      const waypointList = wayPointData.map((item) => ({
        name: item.name,
        id: item.name,
      }));
      typesWaypointLists.value = waypointList;
    }
    const [airportDefault, routeDefault, airRouteDefault] = await Promise.all([
      loadDefaultValues(1, 1), // RAIM机场预测默认值
      loadDefaultValues(1, 5), // RAIM航路预测默认值
      loadDefaultValues(1, 7), // RAIM航线预测默认值
    ]);
    if (airportDefault) {
      serviceFormData.value[0].data = {
        ...serviceFormData.value[0].data,
        optionsListSatsysDefault: airportDefault.params.satSysId || "",
        optionsListAngleDefault: airportDefault.params.angleId || "",
        optionsListAlgorithmDefault: airportDefault.params.algorithmId || "",
        airports: Array.isArray(airportDefault.airportCodes)
          ? airportDefault.airportCodes
              .slice(0, 5)
              .concat(Array(5 - airportDefault.airportCodes.length).fill(""))
          : ["", "", "", "", ""],
      };
      serviceFormData.value[0].updateKey += 1;
    }
    if (routeDefault) {
      serviceFormData.value[1].data = {
        ...serviceFormData.value[1].data,
        optionsListSatsysDefault5: String(routeDefault.params.satSysId || ""),
        optionsListAngleDefault5: String(routeDefault.params.angleId || ""),
        optionsListAlgorithmDefault5: String(
          routeDefault.params.algorithmId || ""
        ),
        stdId5: String(routeDefault.params.stdId || ""),
        routeCode5: routeDefault.routeCode || "",
      };
      serviceFormData.value[1].updateKey += 1;
    }
    if (airRouteDefault) {
      const routeSegmentsNewArr = airRouteDefault.segments.map((item) => {
        return {
          entryWaypointName: item.entryWaypointName,
          routeCode: item.routeCode,
          exitWaypointName: item.exitWaypointName,
          checked: false,
        };
      });
      serviceFormData.value[2].data = {
        ...serviceFormData.value[2].data,
        optionsListAngleDefault71: String(airRouteDefault.depAngleId || ""),
        optionsListAngleDefault72: String(airRouteDefault.destAngleId || ""),
        optionsListAngleDefault73: String(airRouteDefault.destAngleId || ""),
        airport71: String(airRouteDefault.depAirport.airportCode || ""),
        airport72: String(airRouteDefault.destAirport.airportCode || ""),
        optionsListAlgorithmDefault7: String(
          airRouteDefault.routeAlgorithmId || ""
        ),
        stdId7: String(airRouteDefault.routeStdId || ""),
        optionsListSatsysDefault7: String(airRouteDefault.satSysId || ""),
        selectedstartTimeDateTime7: new Date(airRouteDefault.startTime),
        flightHours7: String(airRouteDefault.flightHours || "0"),
        flightMinutes7: String(airRouteDefault.flightMinutes || "0"),
        routeSegments: routeSegmentsNewArr,
      };
      serviceFormData.value[2].updateKey += 1;
    }
  } catch (error) {
    console.error("初始化下拉选项失败：", error);
  }
};

const loadDefaultValues = async (methods = 1, type = 1) => {
  try {
    const { code: defaultCode, data: defaultData } = await selectionsGetApi(
      methods,
      type
    );
    if (defaultCode === 200 && defaultData) {
      if (type === 1) {
        const rawAirports = defaultData.airportCodes;
        defaultData.airportCodes = Array.isArray(rawAirports)
          ? rawAirports.slice(0, 5)
          : ["", "", "", "", ""];
      }
      return defaultData;
    }
  } catch (error) {
    console.error(`加载默认值(methods=${methods}, type=${type})失败：`, error);
  }
  return { airportCodes: ["", "", "", "", ""] };
};

// 处理航线组件的航路编辑事件（插入/删除/追加）
const handleRouteEdit = (action, serviceIndex) => {
  const targetService = serviceFormData.value[serviceIndex - 1];
  let routeSegments = [...targetService.data.routeSegments];

  switch (action) {
    case "delete": {
      // 删除选中的航路分段
      const selectedIndex = routeSegments.findIndex((item) => item.checked);
      if (selectedIndex !== -1) {
        routeSegments.splice(selectedIndex, 1);
      }
      break;
    }
    case "add": {
      // 关键修复1：读取子组件同步到父组件的最新值（确保拿到填写的入口点/代码/出口点）
      const { typesWaypoint71, routeCode7, typesWaypoint72 } =
        targetService.data;
      if (typesWaypoint71 && routeCode7 && typesWaypoint72) {
        // 关键修复2：生成新数组（而非修改原数组），确保引用变化
        routeSegments = [
          ...routeSegments,
          {
            entryWaypointName: typesWaypoint71,
            routeCode: routeCode7,
            exitWaypointName: typesWaypoint72,
            checked: false,
          },
        ];
      }
      break;
    }
    case "insert": {
      // 原有插入逻辑不变，同样修改为生成新数组
      const insertIndex = routeSegments.findIndex((item) => item.checked);
      const {
        typesWaypoint71: insertWaypoint1,
        routeCode7: insertRouteCode,
        typesWaypoint72: insertWaypoint2,
      } = targetService.data;
      if (
        insertIndex !== -1 &&
        insertWaypoint1 &&
        insertRouteCode &&
        insertWaypoint2
      ) {
        routeSegments = [
          ...routeSegments.slice(0, insertIndex),
          {
            entryWaypointName: insertWaypoint1,
            routeCode: insertRouteCode,
            exitWaypointName: insertWaypoint2,
            checked: false,
          },
          ...routeSegments.slice(insertIndex),
        ];
      }
      break;
    }
  }
  // 生成新的data对象（确保引用变化），触发响应式
  const newData = { ...targetService.data, routeSegments };
  targetService.data = newData;
  updateServiceForm(serviceIndex, targetService.data);
};

// 页面挂载时加载所有选项
onMounted(() => {
  loadAllOptions();
  // 初始触发一次服务1的组件匹配
  handleServiceChange(1);
});

const serviceMap = {
  1: "RAIM机场预测",
  2: "RAIM航路预测",
  3: "RAIM航线预测",
  4: "RAIM区域预测",
  11: "ADS-B航线预测",
  12: "ADS-B区域预测",
};

const getServiceLabel = (value) => {
  return serviceMap[value];
};

// 清空详情索引
const clearDetailIndex = () => {
  window.history.back();
};

watch(
  () => form.pushSetting,
  (newVal) => {
    if (newVal === "1") {
      form.timePoint2 = "";
    }
  },
  { immediate: true } // 初始化时执行一次
);
watch(
  () => form.period,
  (newVal) => {
    if (newVal === "自定义天数") {
      form.cusDay = 1;
    } else {
      form.cusDay = "";
    }
  },
  { immediate: true } // 初始化时执行一次
);
</script>

<style scoped lang="scss">
.form-wrapper {
  margin: 0 auto;
  width: 100%;
  max-width: 600px;
}
.custom-form {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  // background-color: #f5f7fa; /* 背景色，可根据设计调整 */
  border-radius: 8px;
}
:deep(.custom-form) {
  .el-input__wrapper {
    height: 28px !important;
    border: 1px solid #003b7a !important;
    box-shadow: none !important;
    font-size: 12px !important;
  }
  .el-select__wrapper {
    height: 28px !important;
    border: 1px solid #003b7a !important;
    box-shadow: none !important;
    font-size: 12px !important;
  }
  .el-date-editor .el-input__wrapper {
    height: 28px !important;
    border: 1px solid #003b7a !important;
    font-size: 12px !important;
  }
  .el-input__inner {
    font-size: 12px !important;
  }
  .el-select__selected-item {
    font-size: 12px !important;
  }
}
:deep(.custom-form .el-input__inner) {
  color: #fff;
}
:deep(.custom-form .el-form-item__label) {
  color: #fff;
}
.homeContainer {
  display: flex;
  flex-direction: column;
  height: 100%;
  min-width: 1280px;
  position: relative;
  box-sizing: border-box;
  // height: 100%;
  // min-width: 1280px;
  // position: relative;
  // box-sizing: border-box;
}
.deliveryRight {
  float: right;
  overflow: hidden;
  .box {
    font-size: 14px;
    color: #fff;
    cursor: pointer;
    float: right;
    height: 32px;
    line-height: 32px;
    padding: 0px 16px;
    border-radius: 4px;
    border: 1px solid #003b7a;
    background: transparent;
  }
  .boxcur {
    border: 1px solid #00afff;
    background: #00afff;
  }
}
.topBack {
  text-align: left;
  color: #fff;
  font-size: 20px;
  font-weight: 700;
  cursor: pointer;
  // width: 100%;
  margin-left: 24px;
  height: 24px;
  line-height: 24px;
  margin-bottom: 16px;
  margin-top: 22px;
  i {
    float: left;
    width: 24px;
    height: 24px;
    background-image: url("../../assets/images/raim/back.png");
    background-repeat: no-repeat;
    background-size: contain;
    background-position: center;
  }
}
.findRouteBox {
  height: calc(100vh - 94px);
  position: absolute;
  background-color: #06112a;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
  z-index: 1;
}
.centerBox {
  min-width: 1280px;
  width: 100%;
  min-height: calc(100vh - 100px);
  display: flex;
  gap: 10px;
  padding: 15px 15px 0;
  box-sizing: border-box;
}
.centerLeft {
  position: relative;
  width: 100%;
  // max-width: calc(100vw - 440px);
  flex: 1;
  min-width: 790px;
  min-height: 520px;
  height: auto;
  max-height: calc(100vh - 160px);
  border: 2px solid #003b7a;
  box-sizing: border-box;
  flex-shrink: 0;
}
.centerRight {
  width: 370px;
  height: calc(100vh - 160px);
  margin: 0;
  display: flex;
  flex-direction: column;
  box-sizing: border-box;
  .rightTop {
    margin-top: 0;
    flex-wrap: wrap;
    .rightBtn {
      cursor: pointer;
      margin-right: 8px;
      margin-bottom: 8px;
      float: left;
      text-align: center;
      color: #c5d6e6;
      width: 130px;
      height: 32px;
      line-height: 32px;
      font-size: 16px;
      background: rgba(0, 175, 255, 0.1);
    }
    .rightBtnCur {
      color: #1fc6ff;
      border-bottom: 2px solid #1fc6ff;
      background: linear-gradient(
        0deg,
        rgba(31, 198, 255, 0.32) 0%,
        rgba(31, 198, 255, 0) 100%
      );
    }
  }
}
.dingyuerightInfo {
  // overflow: hidden;
  margin-top: 2px;
  position: relative;
  width: 100%;
  // min-height: calc(100vh - 270px);
  height: auto;
  flex: 1;
  padding-top: 6px;
  background-image: url("../../assets/images/raim/rightInfoBox.png");
  background-repeat: no-repeat;
  background-size: 100% 100%;
  background-position: center;
  // overflow-y: auto;
  box-sizing: border-box;
}
.footerTime {
  // position: fixed;
  // left: 0;
  // bottom: 0;
  width: 100%;
  height: 28px;
  background-color: #050d24;
  box-sizing: border-box;
  p {
    color: #fff;
    text-align: right;
    font-size: 12px;
    line-height: 28px;
    padding-right: 16px;
  }
}
.airport-select-container {
  padding: 0 1px;
  height: auto;
  height: calc(100vh - 216px);
  overflow-y: auto;
  box-sizing: border-box;
}

.airport-select-container::-webkit-scrollbar {
  width: 4px;
}
.airport-select-container::-webkit-scrollbar-track {
  background: rgba(6, 15, 37, 0.5);
  border-radius: 2px;
}

.airport-select-container::-webkit-scrollbar-thumb {
  background: rgba(0, 175, 255, 0.4);
  border-radius: 2px;
}

.airport-select-container::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 175, 255, 0.6);
}

.airport-select-container {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 175, 255, 0.4) rgba(6, 15, 37, 0.5);
}
.select-item {
  margin-bottom: 12px;
}
.select-item7 {
  margin-bottom: 12px;
  width: 140px;
  float: left;
  margin-right: 12px;
}
.select-item7:nth-child(even) {
  float: left;
  margin-right: 0px;
}

::v-deep .select-item7short .el-input {
  float: left;
  width: 56px;
  height: 28px;
}
::v-deep .select-item7short .boxspan {
  float: left;
  margin: 0 5px;
  font-size: 12px;
  color: #fff;
  line-height: 28px;
}
::v-deep .innerBox {
  overflow-y: auto;
  height: 96px;
  .white-text-checkbox {
    margin-bottom: 0;
    line-height: 32px;
    .el-checkbox__inner {
      background-color: transparent;
    }
  }
}
::v-deep .routerName {
  border: 1px solid #003b7a;
  padding: 5px 12px;
  padding-top: 3px;

  .el-checkbox__label {
    vertical-align: text-top;
    color: #fff;
  }
  .innerBox::-webkit-scrollbar {
    width: 4px;
  }
  .innerBox::-webkit-scrollbar-track {
    background: rgba(6, 15, 37, 0.5);
    border-radius: 2px;
  }

  .innerBox::-webkit-scrollbar-thumb {
    background: rgba(0, 175, 255, 0.4);
    border-radius: 2px;
  }

  .innerBox::-webkit-scrollbar-thumb:hover {
    background: rgba(0, 175, 255, 0.6);
  }

  .innerBox {
    scrollbar-width: thin;
    scrollbar-color: rgba(0, 175, 255, 0.4) rgba(6, 15, 37, 0.5);
  }
}
::v-deep .el-input__wrapper {
  background-color: transparent;
  box-shadow: none;
  color: #fff;
  border: 1px solid #003b7a;
}

.kindBtnChanges {
  margin-bottom: 8px;
  position: relative;
  overflow: hidden;
  .btnBox {
    margin-right: 12px;
    cursor: pointer;
    height: 32px;
    padding: 6px 4px;
    float: left;
    border-radius: 4px;
    border: 1px solid #003b7a;
    font-size: 14px;
    color: #fff;
    background: transparent;
  }
  .btnBoxCur {
    background: #00afff;
  }
}

.select-item label {
  text-align: left;
  display: block;
  font-size: 14px;
  margin-bottom: 4px;
  color: #fff !important;
}

.el-select {
  width: 100%;
  // border: 1px solid #003b7a;
}
::v-deep .custom-select-container {
  padding: 4px 16px;
}
::v-deep .custom-select-container .el-select__wrapper {
  background: transparent;
  box-shadow: none;
  height: 32px;
  min-height: 32px;
}
::v-deep .custom-select-container .el-select__selected-item {
  color: #fff !important;
}
::v-deep .custom-select-container .el-select__caret {
  color: #fff !important;
}
::v-deep .custom-select-container .el-scrollbar {
  background-color: #334155;
}
/* 下拉菜单容器样式 */
::v-deep .custom-select-container .el-select-dropdown {
  background-color: #1e293b;
  border: 1px solid #334155;
  box-shadow: none;
}

.el-select-dropdown__item {
  font-size: 12px;
  height: 28px !important;
  line-height: 28px !important;
  background-color: #060f25;
  color: #fff;
}

.el-select-dropdown__item:hover {
  background-color: #0c1e4b;
  color: #fff;
}

.el-select-dropdown__item.is-selected {
  background-color: #0c1e4b;
  color: #0083cf !important;
}
.el-select-dropdown__item.is-hovering {
  background-color: #0c1e4b;
  color: #fff;
}

:deep(.el-date-editor.el-input) {
  /* width: 356px; */
  width: 100%;
  height: 28px;
  font-size: 12px;
}
:deep(.el-date-editor.el-input .el-input__wrapper) {
  color: #fff;
  background: transparent;
  border: 1px solid #003b7a;
  box-shadow: none;
}
:deep(.el-date-editor.el-input .el-input__inner) {
  color: #fff;
}

/* 自定义表格样式 */
::v-deep .custom-table .el-table__header {
  height: 40px;
  line-height: 40px;
  background: rgba(0, 175, 255, 0.2);
}
::v-deep .custom-table .el-table__header th {
  font-size: 12px;
  font-weight: 700;
  background: rgba(0, 175, 255, 0.2);
  color: #ffffff;
}
::v-deep .custom-table .el-table__row:nth-child(even) {
  background: rgba(0, 59, 122, 0.2) !important;
}
::v-deep .custom-table .el-table__row:nth-child(odd) {
  background-color: transparent;
}
::v-deep .custom-table .el-table__body td {
  color: #ffffff;
}
/* 自定义分页样式 */
.custom-pagination {
  /* float: right;
  margin-top: 20px; */
  position: absolute;
  right: 40px;
  bottom: 40px;
}
.custom-pagination .el-pagination__total {
  color: #ffffff;
}
.custom-pagination .el-pagination__sizes {
  color: #ffffff;
}
.custom-pagination .el-pagination__sizes .el-input__inner {
  background-color: transparent;
  color: #ffffff;
  border: 1px solid #3e465e;
}
.custom-pagination .el-pagination__sizes .el-input__inner:hover {
  border-color: #4aadf8;
}
.custom-pagination .el-pagination__btn {
  background-color: transparent;
  color: #ffffff;
  border: 1px solid #3e465e;
}
.custom-pagination .el-pagination__btn:hover {
  background-color: #4aadf8;
  border-color: #4aadf8;
}

.custom-pagination .el-pagination__active {
  background-color: #00a2ff;
  color: #ffffff;
  border: 1px solid #00a2ff;
}
.custom-pagination .el-pagination__jump {
  color: #ffffff;
}
.custom-pagination .el-input__inner {
  background-color: transparent;
  color: #ffffff;
  border: 1px solid #3e465e;
}
.custom-pagination .el-input__inner:hover {
  border-color: #4aadf8;
}
::v-deep .tableScrollBox {
  height: 676px;
  overflow-y: auto;
}

::v-deep .tableScrollBox::-webkit-scrollbar {
  width: 2px;
}
::v-deep .tableScrollBox::-webkit-scrollbar-track {
  background: rgba(6, 15, 37, 0.5);
  border-radius: 2px;
}

::v-deep .tableScrollBox::-webkit-scrollbar-thumb {
  background: rgba(0, 175, 255, 0.4);
  border-radius: 2px;
}

::v-deep .tableScrollBox::-webkit-scrollbar-thumb:hover {
  background: rgba(0, 175, 255, 0.6);
}

::v-deep .tableScrollBox {
  scrollbar-width: thin;
  scrollbar-color: rgba(0, 175, 255, 0.4) rgba(6, 15, 37, 0.5);
}
/* 表格容器背景透明 */
:deep(.el-table) {
  background-color: transparent !important;
  border: none;
}
:deep(.el-table__body tr) {
  background-color: transparent !important;
}

:deep(.el-table__header tr) {
  color: #c5d6e6;
  font-size: 12px;
  font-weight: 400;
  line-height: 20px;
  background-color: transparent !important;
}
/* 斑马线样式：偶数行 */
:deep(.table-row-even) {
  background-color: rgba(0, 59, 122, 0.2) !important;
}

/* 斑马线样式：奇数行 */
:deep(.table-row-odd) {
  background-color: transparent !important;
}

/* 表格行hover效果 */
:deep(.el-table__row:hover > td) {
  background-color: rgba(0, 59, 122, 0.2) !important;
}

/* 去掉表格默认边框线 */
:deep(.el-table__inner-wrapper::before) {
  background-color: transparent !important;
}
:deep(.el-table__cell) {
  border-bottom: none !important;
}
/* 关键：修改斑马线行的单元格背景色 */
:deep(
    .el-table--striped
      .el-table__body
      tr.el-table__row--striped
      td.el-table__cell
  ) {
  padding: 0;
  background-color: rgba(0, 59, 122, 0.2) !important;
}
:deep(.el-table .cell) {
  padding-right: 0 !important;
}
:deep(.el-pagination__sizes) {
  color: #fff;
}
:deep(.el-pagination__total) {
  color: #fff;
}
:deep(.el-pagination__jump) {
  color: #fff;
}
:deep(.el-pager li) {
  background-color: transparent !important;
  color: #fff;
  border: 1px solid #3e465e;
}
:deep(.el-pager li:hover) {
  background-color: #4aadf8 !important;
  color: #fff;
  border: 1px solid #4aadf8;
}
:deep(.el-pager .is-active) {
  background-color: #4aadf8 !important;
  color: #fff;
  border: 1px solid #4aadf8;
}
:deep(.el-pagination button),
:deep(.el-select__wrapper),
:deep(.el-input__wrapper) {
  background-color: transparent !important;
  color: #fff !important;
  border: 1px solid #003b7a;
  box-shadow: none;
}
:deep(.el-pagination .el-input__inner),
:deep(.el-select__placeholder) {
  color: #fff;
}
.tabBox {
  // height: 538px;
}
</style>
